<template>
  <div class="profile-container">
    <div class="profile-header">
      <h1>{{ userInfo.username }}的个人中心</h1>
      <button @click="goBack" class="back-button">返回</button>
    </div>
    
    <div class="profile-content">
      <div class="profile-info">
        <div class="info-item">
          <span class="info-label">个性签名：</span>
          <span class="info-value">{{ userInfo.personalSignature }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">生日：</span>
          <span class="info-value">{{ userInfo.birthday }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">文章数：</span>
          <span class="info-value">{{ userInfo.articleCount }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">用户ID：</span>
          <span class="info-value">{{ userInfo.id }}</span>
        </div>
        <!-- 邮箱按钮放置在个人简介的右下角 -->
        <div class="email-button-container">
          <button @click="goToEmail" class="email-button">个人邮箱</button>
        </div>
      </div>
    </div>

    <div class="articles-container">
      <div class="tabs">
        <button 
          v-for="(tab, index) in tabs" 
          :key="index" 
          :class="['tab-button', { active: selectedTab === tab.value }]" 
          @click="selectedTab = tab.value"
        >
          {{ tab.label }}
        </button>
      </div>
      <div class="article-list" v-if="articles && articles.length > 0">
        <div class="batch-actions" v-if="selectedTab === 'myBlogs' || selectedTab === 'unapproved'">
          <button @click="toggleSelectAll" class="select-all-button">全选</button>
          <button @click="batchDeleteArticles" class="batch-delete-button">批量删除</button>
        </div>
        <div class="article-item" v-for="article in pagedArticles" :key="article.id">
          <div class="checkbox-container" v-if="selectedTab === 'myBlogs' || selectedTab === 'unapproved'">
            <input type="checkbox" :value="article" v-model="selectedArticles" />
          </div>
          <h3>{{ article.title }}</h3>
          <div class="article-meta">
            <span>分区：{{ article.category }}</span>
            <span>作者：{{ article.writer }}</span>
            <span>发布时间：{{ article.publishTime }}</span>
            <span v-if="selectedTab === 'unapproved'">审核状态：未通过</span>
          </div>
          <div class="article-actions">
            <button @click="viewArticle(article)" class="view-button">查看内容</button>
            <button v-if="selectedTab === 'myBlogs' || selectedTab === 'unapproved'" @click="deleteArticle(article)" class="delete-button">删除</button>
            <button v-if="selectedTab === 'unapproved'" @click="showModifyModal(article)" class="modify-button">修改</button>
          </div>
        </div>

        <div class="pagination">
          <button :disabled="currentPage === 1" @click="prevPage" class="pagination-button">上一页</button>
          <span class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
          <button :disabled="currentPage === totalPages" @click="nextPage" class="pagination-button">下一页</button>
        </div>
      </div>
      <div v-else>
        <p>暂无文章</p>
      </div>
    </div>

    <div v-if="showModifyModalFlag" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeModifyModal">&times;</span>
        <h2>修改文章</h2>
        <textarea v-model="modifyArticleContent" rows="10" cols="50"></textarea>
        <div class="modal-actions">
          <button @click="submitModifyArticle" class="submit-button">重新上传</button>
          <button @click="closeModifyModal" class="cancel-button">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import { useRouter } from 'vue-router';

export default defineComponent({
  data() {
    return {
      userInfo: {
        username: '',
        personalSignature: '',
        birthday: '',
        articleCount: 0,
        id: ''
      }, // 用户信息
      selectedTab: 'myBlogs', // 当前选中的选项卡，默认为"我的博客"
      tabs: [
        { label: '我的博客', value: 'myBlogs' },
        { label: '未通过审核', value: 'unapproved' },
        { label: '我的收藏', value: 'myFavorites' },
        { label: '点赞过', value: 'myLikes' },
        { label: '评论过', value: 'myComment' },
        { label: '浏览过', value: 'myBrowsed' }
      ], // 选项卡列表
      articles: [], // 文章列表
      currentPage: 1, // 当前页码
      pageSize: 5, // 每页显示的文章数,
      selectedArticles: [], // 选中的文章
      showModifyModalFlag: false, // 是否显示修改模态框
      currentModifyArticle: null, // 当前正在修改的文章
      modifyArticleContent: '' // 修改后的文章内容
    };
  },
  setup() {
    const router = useRouter();
    return { router };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.articles.length / this.pageSize);
    },
    pagedArticles() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.articles.slice(start, end);
    }
  },
  created() {
    this.fetchUserInfo(); // 获取用户信息
    this.fetchUserProfileData(); // 获取文章列表
  },
  methods: {
    fetchUserInfo() {
      const storedUserInfo = localStorage.getItem('userInfo');
      if (storedUserInfo) {
        this.userInfo = JSON.parse(storedUserInfo);
      }
    },
    goBack() {
      this.router.push('/user-dashboard');
    },
    async fetchUserProfileData() {
      const token = localStorage.getItem('token');
      const username = localStorage.getItem('username');
      if (!token || !username) {
        return;
      }

      try {
        let apiUrl;
        if (this.selectedTab === 'unapproved') {
          apiUrl = 'http://localhost:8080/lzl_content2_war_exploded/userGetUnapprovedArticles';
        } else {
          apiUrl = 'http://localhost:8080/lzl_content2_war_exploded/userProfilePrint';
        }

        const response = await fetch(`${apiUrl}?username=${username}&type=${this.selectedTab}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          }
        });

        const data = await response.json();

        if (response.ok) {
          this.articles = data;
          this.currentPage = 1; // 重置到第一页
        } else {
          alert('获取文章信息失败！');
        }
      } catch (error) {
        console.error('Error fetching user profile data:', error);
        alert('获取文章信息时出错！');
      }
    },
    viewArticle(article) {
      this.router.push({
        name: 'article',
        query: { article: JSON.stringify(article) }
      });
    },
    async deleteArticle(article) {
      const token = localStorage.getItem('token');
      if (!token) {
        return;
      }

      try {
        const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/managerArticleDelete', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            writer: article.writer,
            title: article.title,
            category: article.category
          })
        });

        if (response.ok) {
          alert('删除成功！');
          this.fetchUserProfileData(); // 刷新文章列表
        } else {
          alert('删除失败！');
        }
      } catch (error) {
        console.error('Error deleting article:', error);
        alert('删除时出错！');
      }
    },
    async batchDeleteArticles() {
      if (this.selectedArticles.length === 0) {
        alert('请至少选择一篇文章！');
        return;
      }

      const token = localStorage.getItem('token');
      if (!token) {
        return;
      }

      try {
        const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/managerArticleDeleteBatch', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            articles: this.selectedArticles.map(article => ({
              writer: article.writer,
              title: article.title,
              category: article.category
            }))
          })
        });

        if (response.ok) {
          alert('批量删除成功！');
          this.selectedArticles = []; // 清空选中状态
          this.fetchUserProfileData(); // 刷新文章列表
        } else {
          alert('批量删除失败！');
        }
      } catch (error) {
        console.error('Error deleting articles in batch:', error);
        alert('批量删除时出错！');
      }
    },
    toggleSelectAll() {
      if (this.selectedArticles.length === this.pagedArticles.length) {
        this.selectedArticles = [];
      } else {
        this.selectedArticles = [...this.pagedArticles];
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    showModifyModal(article) {
      this.currentModifyArticle = article;
      this.modifyArticleContent = article.content;
      this.showModifyModalFlag = true;
    },
    closeModifyModal() {
      this.showModifyModalFlag = false;
      this.currentModifyArticle = null;
      this.modifyArticleContent = '';
    },
    async submitModifyArticle() {
      if (!this.currentModifyArticle) {
        return;
      }

      const token = localStorage.getItem('token');
      if (!token) {
        return;
      }

      try {
        const response = await fetch('http://localhost:8080/lzl_content2_war_exploded/userModifyArticle', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            writer: this.currentModifyArticle.writer,
            title: this.currentModifyArticle.title,
            category: this.currentModifyArticle.category,
            content: this.modifyArticleContent
          })
        });
        const data = await response.json(); // 解析响应体
        if (response.ok) {
          alert('修改成功！');
          this.closeModifyModal();
          this.fetchUserProfileData(); // 刷新文章列表
        } else {
          alert(`修改失败！${data.message || '未知错误'}`);
        }
      } catch (error) {
        console.error('Error modifying article:', error);
        alert('修改时出错！');
      }
    },
    goToEmail() {
      this.router.push('/email');
    }
  },
  watch: {
    selectedTab: function(newTab) {
      this.fetchUserProfileData();
    }
  }
});
</script>

<style scoped>
.profile-container {
  font-family: Arial, sans-serif;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #4CAF50;
}

h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.back-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.back-button:hover {
  background-color: #45a049;
}

.profile-content {
  padding: 20px;
  background-color: #f9f9f9;
  border: 1px solid #eee;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: relative; /* 添加定位属性 */
}

.profile-info {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.info-label {
  font-weight: bold;
  color: #555;
  min-width: 100px;
}

.info-value {
  color: #333;
  word-break: break-word;
}

.articles-container {
  margin-top: 30px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 10px;
}

.tab-button {
  margin-right: 20px;
  padding: 8px 15px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
  color: #666;
  border-radius: 4px;
  transition: all 0.3s;
}

.tab-button.active {
  color: #4CAF50;
  font-weight: bold;
  background-color: #f0f9f0;
}

.article-list {
  margin-top: 20px;
}

.article-item {
  border: 1px solid #eee;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 5px;
  background-color: #fff;
  position: relative;
}

.checkbox-container {
  position: absolute;
  top: 15px;
  right: 15px;
}

.article-item h3 {
  margin-top: 0;
  color: #333;
}

.article-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 10px 0;
  color: #666;
}

.article-actions {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.view-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.view-button:hover {
  background-color: #0b7dda;
}

.delete-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: 10px;
}

.delete-button:hover {
  background-color: #d32f2f;
}

.modify-button {
  background-color: #FFC107;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: 10px;
}

.modify-button:hover {
  background-color: #FFA000;
}

.batch-actions {
  margin-bottom: 15px;
}

.batch-delete-button, .select-all-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-right: 10px;
}

.batch-delete-button:hover, .select-all-button:hover {
  background-color: #d32f2f;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin: 0 10px;
}

.pagination-button:hover {
  background-color: #0b7dda;
}

.pagination-button:disabled {
  background-color: #f1f1f1;
  color: #999;
  cursor: not-allowed;
}

.page-info {
  margin: 0 10px;
  color: #666;
}

.modal {
  display: block;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 600px;
  border-radius: 5px;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}

.close:hover {
  color: black;
}

.modal-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.submit-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.cancel-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

/* 邮箱按钮样式 */
.email-button-container {
  position: absolute;
  bottom: 20px;
  right: 20px;
}

.email-button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
}

.email-button:hover {
  background-color: #0b7dda;
}
</style>